package com.zen.android.sample.scananim;

import java.util.ArrayList;
import java.util.List;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.os.Handler;
import android.os.SystemClock;
import android.view.Gravity;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;

import com.zen.android.sample.R;

/**
 * @author zeng
 * @date 2017年12月18日
 * @Description:
 */
public class ViewUtils {
    /*
	 * 功能介绍：自动创建view，然后跑动画，跑完动画自动销毁，view的位置随机生成
	 */

    private FrameLayout mParentLayout;
    private int mParentWidth, mParentHeight;
    private View mCenterView;
    private int mCenterHeight;
    private boolean mIsStop = false;

    private Handler mHandler;

    private long mAnimTime = 1000;
    private long mCreateTime = 300;

    private static final int LEFTTOP = 0;
    private static final int LEFTBOTTOM = 1;
    private static final int RIGHTTOP = 2;
    private static final int RIGHTBOTTOM = 3;

    private static final float BALLSCALE = 0.5f;

    private int minL;
    private int maxL;
    private int minR;
    private int maxR;

    private static final int MSG_ADD = 11;
    private List<View> mViews = new ArrayList<View>();

    public ViewUtils(FrameLayout pParentLayout, int width, int height) {
        // TODO Auto-generated constructor stub
        this.mParentLayout = pParentLayout;
        mParentWidth = width;
        mParentHeight = height;
        init();
        mCenterView = createCenterView();
        mHandler = new Handler() {
            public void handleMessage(android.os.Message msg) {
                //
                switch (msg.what) {
                    case MSG_ADD:
                        int type = (int) (Math.random() * 4);
                        createView(type, getViewLoc(type));
                        type = (int) (Math.random() * 4);
                        createView(type, getViewLoc(type));
                        // int type = 0;// (int) (Math.random() * 4);
                        // createView(type, getViewLoc(type));
                        // type = 1;// (int) (Math.random() * 4);
                        // createView(type, getViewLoc(type));
                        // type = 2;// (int) (Math.random() * 4);
                        // createView(type, getViewLoc(type));
                        // type = 3;// (int) (Math.random() * 4);
                        // createView(type, getViewLoc(type));
                        break;

                    default:
                        break;
                }
            }

            ;
        };
    }

    private void init() {
        // 2/8-3/8
        // 6/8-7/8;
        mCenterHeight = dip2px(mParentLayout.getContext(), 28);// 28是图片大小...图片56*56px
        // 随机生成view的水平坐标位置区间
        minL = mParentWidth * 1 / 10;
        maxL = mParentWidth * 4 / 10;
        minR = mParentWidth * 6 / 10;
        maxR = mParentWidth * 9 / 10;

    }

    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 创建view时左上角相对父类0.0位置 这个基本可以忽略了，属性动画之惯性从哪里开始，所以这个方法无效
     *
     * @param @param  type
     * @param @return 参数
     * @return int[] 返回类型
     * @throws
     * @Title: getViewLoc
     * @Description: TODO(这里用一句话描述这个方法的作用)
     */
    private int[] getViewLoc(int type) {
        int[] arr = new int[2];// x,y
        switch (type) {
            case LEFTTOP:
                arr[0] = 0;// (int) (Math.random() * minL + (maxL - minL));
                break;
            case LEFTBOTTOM:
                arr[0] = 0;// (int) (Math.random() * minL + (maxL - minL));
                arr[1] = mParentHeight - mCenterHeight;
                break;
            case RIGHTTOP:
                arr[0] = minR;// (int) (Math.random() * minR + (maxR - minR));
                break;
            case RIGHTBOTTOM:
                arr[0] = minR;// (int) (Math.random() * minR + (maxR - minR));
                arr[1] = mParentHeight;
                break;
            default:
                break;
        }
        return arr;
    }

    /**
     * 基准点，没作用，看效果
     *
     * @param @return 参数
     * @return View 返回类型
     * @throws
     * @Title: createCenterView
     * @Description: TODO(这里用一句话描述这个方法的作用)
     */
    private View createCenterView() {
        View view = new View(mParentLayout.getContext());
        view.setBackgroundResource(R.drawable.scan_anim_top_animation_circle);
        LayoutParams lps = new LayoutParams((int) (mCenterHeight * BALLSCALE),
                (int) (mCenterHeight * BALLSCALE));
        lps.gravity = Gravity.CENTER;
        // mParentLayout.addView(view, lps);
        return view;
    }

    private int[] getAnimParams(int type, int[] loc) {
        int[] arr = new int[4];// x,y
        int offset = (int) (mCenterHeight * BALLSCALE) / 2;// 不要最终多集结在一个点上
        switch (type) {
            case LEFTTOP:

                arr[0] = (int) (Math.random() * (maxL - minL) + minL);

                arr[1] = mParentWidth / 2 - mCenterHeight / 2 - offset;
                arr[2] = -mCenterHeight;
                arr[3] = (int) (mParentHeight / 2 - mCenterHeight * BALLSCALE)
                        - offset;
                break;
            case LEFTBOTTOM:
                arr[0] = (int) (Math.random() * (maxL - minL) + minL);
                arr[1] = (mParentWidth / 2 - mCenterHeight / 2) - offset;// (mParentWidth
                // / 2 -
                // mCenterHeight);
                arr[2] = mParentHeight;
                arr[3] = mParentHeight / 2 - mCenterHeight / 2 + offset;// -mCenterHeight;//((int)
                // (mParentHeight
                // / 4));
                break;
            case RIGHTTOP:
                arr[0] = (int) (Math.random() * (maxR - minR) + minR);
                arr[1] = (mParentWidth / 2 - mCenterHeight / 2) + offset;
                arr[2] = -mCenterHeight;
                arr[3] = (int) (mParentHeight / 2 - mCenterHeight * BALLSCALE)
                        - offset;
                break;
            case RIGHTBOTTOM:
                arr[0] = (int) (Math.random() * (maxR - minR) + minR);
                arr[1] = (mParentWidth / 2 - mCenterHeight / 2) + offset;// (mParentWidth
                // / 2 -
                // mCenterHeight);
                arr[2] = mParentHeight;
                arr[3] = mParentHeight / 2 - mCenterHeight / 2 + offset;// -mCenterHeight;//((int)
                // (mParentHeight
                // / 4));
                break;
            default:
                break;
        }
        return arr;
    }

    /**
     * 创建一个view
     *
     * @param @return 参数
     * @return View 返回类型
     * @throws
     * @Title: createView
     * @Description: TODO(这里用一句话描述这个方法的作用)
     */
    private View createView(int type, int[] pArr) {
        final View view = new View(mParentLayout.getContext());
        view.setBackgroundResource(R.drawable.scan_anim_top_animation_circle);
        LayoutParams lps = new LayoutParams(mCenterHeight, mCenterHeight);
        view.setX(pArr[0]);
        view.setY(pArr[1]);
        mParentLayout.addView(view, lps);

        mViews.add(view);
        createAnimator(view, getAnimParams(type, pArr));
        // Animation anim = createAnim(getAnimParams(type, pArr));
        // anim.setAnimationListener(new AnimationListener() {
        //
        // @Override
        // public void onAnimationStart(Animation animation) {
        // // TODO Auto-generated method stub
        //
        // }
        //
        // @Override
        // public void onAnimationRepeat(Animation animation) {
        // // TODO Auto-generated method stub
        //
        // }
        //
        // @Override
        // public void onAnimationEnd(Animation animation) {
        // // TODO Auto-generated method stub
        // // view.setVisibility(View.GONE);
        // // mViews.remove(view);
        // }
        // });
        // view.startAnimation(anim);
        return view;
    }

    private Animator createAnimator(final View pView, int[] pArr) {
        ObjectAnimator scaleAnimator = ObjectAnimator.ofFloat(pView, "scaleX",
                1f, BALLSCALE);
        ObjectAnimator scaleAnimatorY = ObjectAnimator.ofFloat(pView, "scaleY",
                1f, BALLSCALE);
        ObjectAnimator transAnimatorX = ObjectAnimator.ofFloat(pView,
                "translationX", pArr[0], pArr[1]);
        ObjectAnimator transAnimatorY = ObjectAnimator.ofFloat(pView,
                "translationY", pArr[2], pArr[3]);
        AnimatorSet ob = new AnimatorSet();
        ob.playTogether(scaleAnimator, transAnimatorX, scaleAnimatorY,
                transAnimatorY);
        ob.setDuration(mAnimTime);
        ob.setInterpolator(new AccelerateDecelerateInterpolator());

        ob.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                // TODO Auto-generated method stub
                super.onAnimationEnd(animation);
                pView.setVisibility(View.GONE);
                mViews.remove(pView);
            }
        });
        ob.start();
        return ob;
    }

    private Animation createAnim(int[] pArr) {
        // Animation mScaleAnimation = new
        // ScaleAnimation(pArr[0],mTargetX,pArr[1],mTargetY);
        ScaleAnimation mScaleAnimation = new ScaleAnimation(1, BALLSCALE, 1,
                BALLSCALE, Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f);
        mScaleAnimation.setDuration(mAnimTime);

        Animation mTranslateAnimation = new TranslateAnimation(pArr[0],
                pArr[1], pArr[2], pArr[3]);// 移动
        // Animation mTranslateAnimation = new
        // TranslateAnimation(Animation.RELATIVE_TO_SELF, 0,
        // Animation.RELATIVE_TO_PARENT, 0.5f, Animation.RELATIVE_TO_SELF, 0,
        // Animation.RELATIVE_TO_PARENT,0.5f);
        // Animation mTranslateAnimation = new
        // TranslateAnimation(Animation.RELATIVE_TO_SELF, pArr[0],
        // Animation.RELATIVE_TO_SELF, pArr[1], Animation.RELATIVE_TO_SELF,
        // pArr[2], Animation.RELATIVE_TO_SELF, pArr[3]);
        // Animation mTranslateAnimation = new TranslateAnimation(pArr[0],
        // mTargetX, pArr[1], mTargetY);// 移动
        mTranslateAnimation.setDuration(mAnimTime);
        AnimationSet as = new AnimationSet(true);
        as.setInterpolator(new AccelerateDecelerateInterpolator());
        as.setDuration(mAnimTime);
        as.addAnimation(mScaleAnimation);
        as.addAnimation(mTranslateAnimation);
        as.setFillAfter(false);

        return as;
    }

    /**
     * @return void 返回类型
     * @throws
     * @Title: start
     * @Description: TODO(这里用一句话描述这个方法的作用)
     */
    public void start() {
        mIsStop = false;
        new Thread(new Runnable() {
            int count = 0;

            @Override
            public void run() {
                // TODO Auto-generated method stub

                while (!mIsStop) {
                    mHandler.sendEmptyMessage(MSG_ADD);
                    SystemClock.sleep(mCreateTime);
                    // if (count > 5) {
                    // mIsStop = true;
                    // }
                    // count++;
                }
                //

            }
        }).start();
    }

    public void stop() {
        mIsStop = true;
        mHandler.removeCallbacksAndMessages(null);
    }

    public void onDestroy() {
        // 这里一定要把动画移除掉，否则可能崩溃，
        if (!mIsStop) {
            stop();
        }
        //
        try {
            for (View v : mViews) {
                v.clearAnimation();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        mViews.clear();
        mParentLayout.removeAllViews();
        mParentLayout = null;
    }
}
